using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlan;
using ERP_SaaS_WinForm.生产计划_派单_车间;
using ERP_SaaS_WinForm.销售.Sales;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SaleApiResponse = ERP_SaaS_WinForm.销售.Sales.SaleApiResponse;
using ERP_SaaS_WinForm.登录.Model;

namespace ERP_SaaS_WinForm.销售
{
    public partial class Sale : Form
    {
        public Sale()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 客户查询按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void dtnCha_Click(object sender, EventArgs e)
        {
            //Api基础地址
            string baseUrl = "http://localhost:5054/api/Client/GetClient";

            string clientName=txtClientName.Text.Trim();//查询客户名称 Trim是消除空格
            //创建查询的参数列表
            var queryParams=new List<string>();
            if (!string.IsNullOrEmpty(clientName)) queryParams.Add($"clientName={clientName}") ;
            //拼接
            string fullUrl = $"{baseUrl}?{string.Join("&",queryParams)}";
            //使用HttpClient发送请求
            using (HttpClient client=new HttpClient())
            {
                //异步发送Ger请求
                HttpResponseMessage response=await client.GetAsync(fullUrl) ;
                // 确保响应成功（否则抛出异常）
                response.EnsureSuccessStatusCode();
                // 读取响应内容为字符串
                string jsonResponse =await response.Content.ReadAsStringAsync() ;
                // 反序列化 JSON 响应到 SaleApiResponse 对象
                SaleApiResponse apiResponse =JsonConvert.DeserializeObject<SaleApiResponse>(jsonResponse) ;
                // 检查 API 响应码
                if (apiResponse.code == 200)
                {
                    // 将数据绑定到 DataGridView
                    dgvClinent.DataSource = apiResponse.data ;
                    // 如果存在 clientName 列，隐藏它
                    if (dgvClinent.Columns.Contains("clientName"))
                    {
                        dgvClinent.Columns["clientName"].Visible = false;
                    }
                }
                else
                {
                    // 显示错误信息
                    MessageBox.Show($"查询失败{apiResponse.msg}");
                }
            };
         

        }

        private async void Sale_Load(object sender, EventArgs e)
        {
            //调用查询方法
            dtnCha_Click(sender, e);//客户显示
            dtnClientPrice_Click(sender, e);//客户单价显示
            // 初始化新增页编号
            if (txtClientPriceCode != null)
            {
                txtClientPriceCode.Text = GenerateClientPriceCode();
            }
            // 初始化客户ID存储
            if (txtClient.Tag == null)
            {
                txtClient.Tag = "";
            }
            
            // 添加DataGridView的CellClick事件处理
            dgvClientPrice.CellClick += DgvClientPrice_CellClick;

            //折扣方案显示
            string DiscountUrl = "http://localhost:5054/api/Discount/GetDiscount";
            using (HttpClient Dclient=new HttpClient())
            {
                HttpResponseMessage responseMessage=await Dclient.GetAsync(DiscountUrl);
                responseMessage.EnsureSuccessStatusCode();
                string DjsonResponse=await responseMessage.Content.ReadAsStringAsync();

                DiscountApiResponse discount=JsonConvert.DeserializeObject<DiscountApiResponse>(DjsonResponse);
                if(discount.code==200)
                {
                    dgvDiscount.DataSource = discount.data;
                }
                else
                {
                    // 显示错误信息
                    MessageBox.Show($"查询失败{discount.msg}");
                }
            }
        }

        private async void dtnClientPrice_Click(object sender, EventArgs e)
        {
            string clientPrice = "http://localhost:5054/api/ClientPrice/GetClientPrice";
            string clientNames = txtClienNames.Text.Trim();//查询客户名称 Trim是消除空格
            //创建查询的参数列表
            var queryParam = new List<string>();
            if (!string.IsNullOrEmpty(clientNames)) queryParam.Add($"clientNames={clientNames}");
            //拼接
            string clientPricefullUrl = $"{clientPrice}?{string.Join("&", queryParam)}";

            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage responses = await client.GetAsync(clientPricefullUrl);
                responses.EnsureSuccessStatusCode();
                string jsonResponses = await responses.Content.ReadAsStringAsync();
                ClientPriceApiResponse apiResponses = JsonConvert.DeserializeObject<ClientPriceApiResponse>(jsonResponses);
                if (apiResponses.code == 200)
                {
                    dgvClientPrice.DataSource = apiResponses.data;
                    if (dgvClientPrice.Columns.Contains("clientNames"))
                    {
                        dgvClientPrice.Columns["clientNames"].Visible = false;
                    }
                }
                else
                {
                    // 显示错误信息  
                    MessageBox.Show($"查询失败{apiResponses.msg}");
                }
            }
        }

        /// <summary>
        /// 自动计算总金额
        /// </summary>
        private void CalculateTotalAmount()
        {
            try
            {
                decimal price = 0;
                decimal quantity = 0;
                decimal totalAmount = 0;

                // 尝试将产品单价和数量转换为小数
                if (!string.IsNullOrEmpty(txtProductPrice.Text) && decimal.TryParse(txtProductPrice.Text, out price) &&
                    !string.IsNullOrEmpty(txtProductQuantity.Text) && decimal.TryParse(txtProductQuantity.Text, out quantity))
                {
                    totalAmount = price * quantity;
                    txtTotalAmount.Text = totalAmount.ToString("F2");
                }
                else
                {
                    txtTotalAmount.Text = "0.00";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("计算总金额时出错: " + ex.Message);
            }
        }

        /// <summary>
        /// 产品单价文本变化事件
        /// </summary>
        private void txtProductPrice_TextChanged(object sender, EventArgs e)
        {
            CalculateTotalAmount();
        }

        /// <summary>
        /// 产品数量文本变化事件
        /// </summary>
        private void txtProductQuantity_TextChanged(object sender, EventArgs e)
        {
            CalculateTotalAmount();
        }

        /// 选择客户按钮点击事件
        private void btnSelectClient_Click(object sender, EventArgs e)
        {
            Client client = new Client();
            if (client.ShowDialog() == DialogResult.OK && client.SelectedClient != null)
            {
                var c = client.SelectedClient;
                txtClient.Text = client.SelectedClient.ClientName;
                // 存储客户ID到Tag属性中（使用ClientId作为数据库主键）
                txtClient.Tag = c.ClientId;
            }
        }

        /// <summary>
        /// 选择产品按钮点击事件
        /// </summary>
        private void btnSelectProduct_Click(object sender, EventArgs e)
        {
            var selectProduct = new SelectProduct();
            if (selectProduct.ShowDialog() == DialogResult.OK && selectProduct.SelectedProduct != null)
            {
                var p = selectProduct.SelectedProduct;
                txtProduct.Text = p.ProductName;
                txtProductCode.Text = p.ProductCode;
                txtProductSpec.Text = p.Specification;
            }
        }

        /// <summary>
        /// 添加客户单价按钮点击事件
        /// </summary>
        private async void btnAddClientPrice_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证输入
                if (string.IsNullOrEmpty(txtClient.Text))
                {
                    MessageBox.Show("请输入客户名称");
                    return;
                }

                // 验证客户ID是否存在
                if (txtClient.Tag == null || txtClient.Tag.ToString() == "0")
                {
                    MessageBox.Show("请先选择有效的客户");
                    return;
                }

                if (string.IsNullOrEmpty(txtProduct.Text))
                {
                    MessageBox.Show("请输入产品名称");
                    return;
                }

                if (string.IsNullOrEmpty(txtProductPrice.Text))
                {
                    MessageBox.Show("请输入产品单价");
                    return;
                }

                if (string.IsNullOrEmpty(txtProductQuantity.Text))
                {
                    MessageBox.Show("请输入产品数量");
                    return;
                }

                // 将输入转换为后端期望的类型（Price/TotalAmount: double，Numder: int）
                if (!double.TryParse(txtProductPrice.Text.Trim(), out double priceValue))
                {
                    MessageBox.Show("单价格式不正确");
                    return;
                }
                if (!int.TryParse(txtProductQuantity.Text.Trim(), out int quantityValue))
                {
                    MessageBox.Show("数量必须为整数");
                    return;
                }
                if (!double.TryParse(txtTotalAmount.Text.Trim(), out double totalAmountValue))
                {
                    MessageBox.Show("总金额格式不正确");
                    return;
                }

                // 创建客户单价对象（与 AddClientPriceCommand 属性对齐）
                var clientPriceData = new
                {
                    ClientPriceCode = txtClientPriceCode.Text.Trim(),
                    ClientId = int.Parse(txtClient.Tag?.ToString() ?? "0"), // 转换为int类型
                    ProductCode = txtProductCode.Text.Trim(),
                    Price = priceValue,
                    Numder = quantityValue,
                    TotalAmount = totalAmountValue,
                    ClientPriceRemark = txtRemark.Text.Trim()
                };

                // 转换为JSON
                string jsonData = JsonConvert.SerializeObject(clientPriceData);

                // 调用API添加客户单价
                string apiUrl = "http://localhost:5054/api/ClientPrice/AddClientPrice";
                using (HttpClient client = new HttpClient())
                {
                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                    HttpResponseMessage response = await client.PostAsync(apiUrl, content);
                    string jsonResponse = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        dynamic result = JsonConvert.DeserializeObject(jsonResponse);
                        if (result != null && result.code == 200)
                        {
                            MessageBox.Show("添加成功");
                            // 清空输入框
                            ClearClientPriceInputs();
                            // 刷新客户单价列表
                            tabControl1.SelectedTab = tabPage2;
                            dtnClientPrice_Click(sender, e);
                            // 为下一次新增生成新编号
                            tabControl1.SelectedTab = tabPage3;
                            txtClientPriceCode.Text = GenerateClientPriceCode();
                        }
                        else
                        {
                            MessageBox.Show("添加失败: " + (result?.msg ?? jsonResponse));
                        }
                    }
                    else
                    {
                        // 显示后端返回的错误详情，便于定位
                        MessageBox.Show($"添加失败：{response.StatusCode}\n{jsonResponse}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("添加客户单价时出错: " + ex.Message);
            }
        }

        /// <summary>
        /// 清空客户单价输入框
        /// </summary>
        private void ClearClientPriceInputs()
        {
            if (txtClientPriceCode != null)
            {
                txtClientPriceCode.Text = GenerateClientPriceCode();
            }
            txtClient.Text = "";
            txtClient.Tag = null; // 清空客户ID
            txtProduct.Text = "";
            txtProductCode.Text = "";
            txtProductSpec.Text = "";
            txtProductPrice.Text = "";
            txtProductQuantity.Text = "";
            txtTotalAmount.Text = "0.00";
            txtRemark.Text = "";
        }
        /// <summary>
        /// 编号自动生成
        /// </summary>
        /// <returns></returns>
        private string GenerateClientPriceCode()
        {
            try
            {
                string prefix = "KHDJ";
                int maxNum = 0;
                if (dgvClientPrice != null && dgvClientPrice.Rows.Count > 0)
                {
                    foreach (DataGridViewRow row in dgvClientPrice.Rows)
                    {
                        if (row.IsNewRow) continue;
                        var value = row.Cells["Column8"] != null ? row.Cells["Column8"].Value?.ToString() : null;
                        if (string.IsNullOrWhiteSpace(value)) continue;
                        if (!value.StartsWith(prefix)) continue;
                        var numPart = value.Substring(prefix.Length);
                        if (int.TryParse(numPart, out int n))
                        {
                            if (n > maxNum) maxNum = n;
                        }
                    }
                }
                return $"{prefix}{(maxNum + 1).ToString("D3")}";
            }
            catch
            {
                return "KHDJ001";
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab == tabPage3)
            {
                txtClientPriceCode.Text = GenerateClientPriceCode();
            }
        }

        /// <summary>
        /// 客户单价DataGridView修改按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void DgvClientPrice_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == dgvClientPrice.Columns["ColumnEditClientPrice"].Index)
            {
                // 获取当前行的客户单价数据
                var row = dgvClientPrice.Rows[e.RowIndex];
                var clientPriceIdObj = row.Cells["Column16"].Value; // Id 列
                int clientPriceId = 0;
                if (clientPriceIdObj != null) int.TryParse(clientPriceIdObj.ToString(), out clientPriceId);
                var priceCode = row.Cells["Column8"].Value?.ToString();
                var clientName = row.Cells["Column9"].Value?.ToString();
                var productCode = row.Cells["Column10"].Value?.ToString();
                var productName = row.Cells["Column11"].Value?.ToString();
                var spec = row.Cells["Column12"].Value?.ToString();
                var price = row.Cells["Column13"].Value?.ToString();
                var quantity = row.Cells["Column14"].Value?.ToString();
                var totalAmount = row.Cells["Column15"].Value?.ToString();
                var remark = row.Cells["Column17"].Value?.ToString();

                // 创建UpdateClientPrice窗体并传递数据
                UpdateClientPrice updateClientPrice = new UpdateClientPrice(
                    clientPriceId,
                    priceCode ?? "", 
                    clientName ?? "", 
                    productCode ?? "", 
                    productName ?? "", 
                    spec ?? "", 
                    price ?? "", 
                    quantity ?? "", 
                    totalAmount ?? "", 
                    remark ?? "");
                
                // 模态打开，完成后根据结果刷新列表
                var dialogResult = updateClientPrice.ShowDialog(this);
                if (dialogResult == DialogResult.OK)
                {
                    // 重新加载客户单价列表
                    dtnClientPrice_Click(this, EventArgs.Empty);
                }
                
                // TODO: 这里可以打开一个修改客户单价的表单
                // 或者直接在当前界面显示修改控件
            }
            else if (e.RowIndex >= 0 && e.ColumnIndex == dgvClientPrice.Columns["ColumnDeleteClientPrice"].Index)
            {
                // 删除当前行
                var row = dgvClientPrice.Rows[e.RowIndex];
                var idObj = row.Cells["Column16"].Value;
                if (idObj == null || !int.TryParse(idObj.ToString(), out int delId) || delId <= 0)
                {
                    MessageBox.Show("未能获取有效的Id，无法删除");
                    return;
                }

                var confirm = MessageBox.Show($"确定要删除编号为 {row.Cells["Column8"].Value?.ToString()} 的客户单价吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (confirm != DialogResult.Yes) return;

                try
                {
                    string url = $"http://localhost:5054/api/ClientPrice/DelClientPrice?clientPriceId={delId}";
                    using (HttpClient http = new HttpClient())
                    {
                        var resp = await http.GetAsync(url);
                        var content = await resp.Content.ReadAsStringAsync();
                        if (resp.IsSuccessStatusCode)
                        {
                            MessageBox.Show("删除成功");
                            dtnClientPrice_Click(this, EventArgs.Empty);
                        }
                        else
                        {
                            MessageBox.Show($"删除失败：{resp.StatusCode}\n{content}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除时出错：{ex.Message}");
                }
            }
        }
    }
}
